package com.arui.rpc.factory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: zhanyurui
 * @Date: 2021-08-10 20:37
 * @Description: return clazz.cast(instance);
 */
public class SingletonFactory {
    private static Map<Class, Object> objectMap = new HashMap<>();

    private SingletonFactory() {}

    public static <T> T getInstance(Class<T> clazz) {
        Object instance = objectMap.get(clazz);
        synchronized (clazz){
            if (instance==null){
                try {
                    instance = clazz.newInstance();
                    objectMap.put(clazz,instance);
                } catch (InstantiationException  | IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
        return clazz.cast(instance);
    }
}
